package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsAdminMapper;
import com.qf.pojo.DtsAdmin;
import com.qf.service.AdminService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author lixu
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private DtsAdminMapper dtsAdminMapper;
    /**
     * 根据用户名查询用户对象 （一个用户对象）
     * @param username
     * @return
     */
    @Override
    public DtsAdmin findDtsAdminByUsername(String username) {
        QueryWrapper<DtsAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("deleted",false);//是否删除  否  是
        //java false  自动映射  mysql：0
        //java true  自动映射  mysql：1
        return dtsAdminMapper.selectOne(queryWrapper);
    }

    /**
     *  查询分页的后台用户
     * @param username
     * @param sort
     * @param order
     * @param page
     * @param limit
     * @return
     */
    @Override
    public IPage<DtsAdmin> findListByQuery(String username, String sort, String order, Integer page, Integer limit) {
        return dtsAdminMapper.selectPage(new Page(page,limit)
                ,new QueryWrapper<DtsAdmin>()
                        .eq(!StringUtils.isEmpty(username),"username",username)
                        .orderBy(!StringUtils.isEmpty(sort),"ASC".equalsIgnoreCase(order),sort)
        );
    }

    /**
     * 添加
     * @param dtsAdmin
     * @return
     */
    @Override
    public DtsAdmin create(DtsAdmin dtsAdmin) {
        dtsAdmin.setAddTime(new Date());
        dtsAdmin.setUpdateTime(new Date());
        //..
        dtsAdmin.setPassword(new BCryptPasswordEncoder().encode(dtsAdmin.getPassword()));
        //保存 返回ID
        dtsAdminMapper.insert(dtsAdmin);
        return dtsAdmin;
    }
}
